﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using GraphMyCode.Client.AssemblyService;
using GraphMyCode.Client.ViewModels;

namespace GraphMyCode.Client.Views
{
	public partial class WelcomePage
	{
		private byte[] assemblyBytes;
		private AssemblyServiceClient client;

		public WelcomePage()
		{
			InitializeComponent();
		}

		private void browseButton_Click(object sender, RoutedEventArgs e)
		{
			var dialog = new OpenFileDialog {Filter = "Assembly|*.exe;*.dll;*.asm"};

			bool? result = dialog.ShowDialog();

			if (result != null && result.Value)
			{
				browseTextBox.Text = dialog.File.Name;
				using (FileStream stream = dialog.File.OpenRead())
				{
					assemblyBytes = new byte[stream.Length];
					stream.Read(assemblyBytes, 0, (int) stream.Length);
				}
			}
			viewMethodGraphButton.IsEnabled = viewClassGraphButton.IsEnabled = viewClassRefGraphButton.IsEnabled = true;

			client = new AssemblyServiceClient();
			client.GetGraphCompleted += ClientGetGraphCompleted;
		}

		void ClientGetGraphCompleted(object sender, GetGraphCompletedEventArgs e)
		{
			waitIndicator.Stop();

			if (e.Error == null)
			{
				((GraphMapViewModel) DataContext).GraphMapDto = e.Result;
				NavigationService.Navigate(new Uri("/Graph", UriKind.Relative));
			}
			else
			{
				ChildWindow errorWin = new ErrorWindow("Error occured.", e.Error.ToString());
				errorWin.Show();
			}

			client.GetGraphCompleted -= ClientGetGraphCompleted;
			client.CloseAsync();
			client = null;
		}

		private void viewClassGraphButton_Click(object sender, RoutedEventArgs e)
		{			
			waitIndicator.Start();
			client.GetGraphAsync(assemblyBytes, ActualWidth, ActualHeight, ExportType.Class);
		}

		private void viewMethodGraphButton_Click(object sender, RoutedEventArgs e)
		{
			waitIndicator.Start();
			client.GetGraphAsync(assemblyBytes, ActualWidth, ActualHeight, ExportType.Method);
		}

		private void viewClassRefGraphButton_Click(object sender, RoutedEventArgs e)
		{

			waitIndicator.Start();
			try
			{
				client.GetGraphAsync(assemblyBytes, ActualWidth, ActualHeight, ExportType.Assembly);				
			}
			catch
			{
				
			}
		}
	}
}